package com.txw.serviceedu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.txw.sercicebase.exceptionhandller.LingqiException;
import com.txw.serviceedu.entity.EduSubject;
import com.txw.serviceedu.entity.excel.SubjectData;
import com.txw.serviceedu.service.EduSubjectService;
import org.springframework.stereotype.Service;

/**
 * 监听器
 */

public class SubjectExelListener extends AnalysisEventListener<SubjectData> {


    public EduSubjectService subjectService;

    public SubjectExelListener() {
    }

    public SubjectExelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /**
     * 一行一行读取excel内容
     *
     * @param subjectData
     * @param analysisContext
     */
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {

        if (subjectData == null) {
            throw new LingqiException(2001, "文件数据为空");
        }
        //判断一级分类是否重复
        EduSubject exisOneSubject = this.exisOneSubject(subjectService, subjectData.getOneSubjectName());
        if (exisOneSubject == null) {  //没有一级分类，进行添加
            exisOneSubject = new EduSubject();
            exisOneSubject.setParentId("0");
            exisOneSubject.setTitle(subjectData.getOneSubjectName());//一级分类名称
            subjectService.save(exisOneSubject);
        }

        //获取一级分类ID值
        String pid = exisOneSubject.getId();
        //判断一级分类是否重复
        EduSubject exisTwoSubject = this.exisTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
        if (exisTwoSubject == null) {
            exisTwoSubject = new EduSubject();
            exisTwoSubject.setParentId(pid);
            exisTwoSubject.setTitle(subjectData.getTwoSubjectName());//一级分类名称
            subjectService.save(exisTwoSubject);
        }
    }

    /**
     * 判断一级分类不能重复添加
     *
     * @param subjectService
     * @param name
     * @return
     */
    private EduSubject exisOneSubject(EduSubjectService subjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    /**
     * 判断二级分类不能重复添加
     *
     * @param subjectService
     * @param name
     * @param pid
     * @return
     */
    private EduSubject exisTwoSubject(EduSubjectService subjectService, String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        EduSubject towSubject = subjectService.getOne(wrapper);
        return towSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
